package aggregate.aggregator.remote;

import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.util.Collection;

/**
 * @author andreivajnaii
 * Representation of the Client Application on the server (Aggregator) side
 */
public class Client {
		
	private String hostname;

	private ClientRemoteInterface client;

	public Client(String hostname) {
		this.hostname = hostname;
	}
	
	public String getHostname() {
		return hostname;
	}
	
	public void setHostname(String hostname) {
		this.hostname = hostname;
	}
	
	/**
	 * Creates a new object representing the Client Application at the
	 * specified hostname connecting to it via RMI
	 */
	public static Client connectToClient(String hostname)
			throws RemoteException, NotBoundException {
		return new Client(hostname).connectToClient();
	}
	
	private Client connectToClient() throws RemoteException, NotBoundException {
		Registry registry = LocateRegistry.getRegistry(hostname, 5002);
		System.out.println("Connecting to " + hostname);
	    client = (ClientRemoteInterface) registry.lookup("ClientApplication");
	    return this;
	}
	
	public void notify(ContentItem item) throws RemoteException {
		client.notify(item);
	}

	public void notify(Collection<ContentItem> content) throws RemoteException {
		System.out.println("notifying " + hostname);
		for (ContentItem item : content) {
			notify(item);
		}
	}

	public void notifyRating(int contentId, double value) throws RemoteException {
		client.notifyRating(contentId, value);
	}

	public void notifyComment(Comment comment) throws RemoteException {
		client.notifyComment(comment);
	}
}
